<template>
	<div class="sendNotice">
		<div class="classIndex_lk classIndex_h">
			<router-link :to="{path: '/class/notice/index', query: {id: path} }" exact>班级通知</router-link>
			<strong><i>></i>发送通知</strong>
		</div>
		<div class="sendNotice_form">
			<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
				<el-form-item label="发送范围" prop="role_id">
					<el-checkbox-group v-model="ruleForm.role_id">
						<el-checkbox :label="6" name="1">老师</el-checkbox>
						<el-checkbox :label="4" name="2">学生</el-checkbox>
						<el-checkbox :label="5" name="3">家长</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="通知标题" prop="title">
					<el-input v-model.trim="ruleForm.title" placeholder="请输入通知标题" maxlength="20"></el-input>
				</el-form-item>
				<el-form-item label="通知内容" prop="content">
					<el-input type="textarea" :rows="6" resize="none" v-model.trim="ruleForm.content" maxlength="200" placeholder="请输入通知内容描述"></el-input>
					<span class="numberWord"><i>{{ruleForm.content.length}}</i>/200</span>
				</el-form-item>
				<el-form-item label="上传附件">
					<div class="">
						<uploader :options="uploadOptions" :autoStart="false" ref="uploader" :file-status-text="statusText" @files-submitted="fileSubmit" @file-removed="fileRemoved" @file-success="fileSuccess" @file-error="fileFail" :class="{ Upactive: isActive }" class="uploader-cr">
							<uploader-unsupport></uploader-unsupport>
							<uploader-btn :directory="false" :attrs="attrs" v-if="selectFileShow" :single="true">
								<span>上传附件</span>
								<i>支持文档类型： doc\xls\xlsx\ppt\pdf\txt\jpg\png\gif</i>
							</uploader-btn>
							<uploader-list v-show="!selectFileShow"></uploader-list>
						</uploader>
					</div>
				</el-form-item>
				<el-form-item class="sendNotice_btn buttonCSS">
					<el-button type="primary" plain @click="resetForm('ruleForm')">取消</el-button>
					<el-button type="primary" @click="submitForm('ruleForm')" v-preventReClick>发布</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!--  -->
		<el-dialog title="图片设置" :visible.sync="tailorViews" width="1000px" custom-class="alBox" :close-on-click-modal="false">
			<div class="tailoring">
				<div class="tailoring_cropper">
					<vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="true" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :fixedBox="option.fixedBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :centerBox="option.centerBox" :high="option.high" :infoTrue="option.infoTrue" @realTime="realTime" :enlarge="option.enlarge">
					</vueCropper>
				</div>
				<div class="buttonCSS cropper_btn">
					<el-button type="primary" @click="tailorViews = false" plain>取消</el-button>
					<el-button type="primary" @click="finish('base64')" v-preventReClick>确定</el-button>
				</div>
			</div>
		</el-dialog>
	</div>
</template>
<script>
export default {
	data() {
		return {
			path: this.$route.query.id,
			ruleForm: {
				title: '',
				role_id: [],
				content: '',
				file_path: '',
			},
			rules: {
				title: [
					{ required: true, message: '请输入通知标题', trigger: 'blur' },
				],
				role_id: [
					{ type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
				],
				content: [
					{ required: true, message: '请输入通知内容', trigger: 'blur' },
				]
			},
			typeNumber: '',
			statusText: {
				success: '上传成功',
				error: '上传出错',
				uploading: '正在上传...',
				paused: '暂停',
				waiting: '等待上传'
			},
			selectFileOrNot: false, //是否选中文件
			uploadOrNot: false, //是否已经上传
			uploadInfo: {
				file_name: '',
				file_path: '',
				file_size: 0
			},
			attrs: {},
			uploadOptions: {
				target: this.BASE_URL + '/api/resource/res_upload',
				testChunks: false,
				headers: { Authorization: `Bearer ` + this.$g.access_token },
			},
			selectFileShow: true, //是否显示选择文件按钮
			uploadRetryTimes: 100, //文件最大重传次数
			isActive: false,
			tailorViews: false,
			modelSrc: '',
			modelView: '',
			previews: '',

			option: {
				img: '',
				size: 1,
				full: false, //full
				outputType: 'png', //输出图片格式
				canMove: true, //能否拖动图片
				fixedBox: false, //截图框固定大小
				original: true, //否显示原始宽高
				canMoveBox: true, //能否拖动截图框
				autoCrop: true, //autoCrop 是否自动生成截图框
				// 只有自动截图开启 宽度高度才生效
				autoCropWidth: 200,
				autoCropHeight: 150,
				centerBox: false, //截图框是否限制在图片里
				high: true //high //是否根据dpr生成适合屏幕的高清图片
			},
		};
	},
	watch: {
		'changData'(val, newval) {
			this.path = sessionStorage.getItem('classId')
		}
	},
	computed: {
		changData() {
			return deep_clone(this.$store.state.changData);
		},
	},
	methods: {
		//图片裁剪后替换原图片
		finish(type) {
			if (type === 'blob') {
				this.$refs.cropper.getCropBlob((data) => {
					this.tailorViews = false
				})
			} else {
				this.$refs.cropper.getCropData((data) => {

					this.modelView = this.dataURLtoFile(data, this.$refs.uploader.uploader.fileList[0].name)
					this.$refs.uploader.uploader.fileList[0].file = this.modelView
					this.$refs.uploader.uploader.files[0].file = this.modelView
					this.$refs.uploader.uploader.fileList[0].size = this.modelView.size
					this.$refs.uploader.uploader.files[0].size = this.modelView.size
					this.$refs.uploader.uploader.fileList[0].uniqueIdentifier = this.modelView.size + "-" + this.$refs.uploader.uploader.fileList[0].name;
					this.$refs.uploader.uploader.fileList[0].chunks[0].endByte = this.modelView.size;

					this.modelSrc = data
					this.tailorViews = false
				})
			}
		},
		//将base64转换为文件
		dataURLtoFile(dataurl, filename) {
			var arr = dataurl.split(','),
				mime = arr[0].match(/:(.*?);/)[1],
				bstr = atob(arr[1]),
				n = bstr.length,
				u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			return new File([u8arr], filename, { type: mime });

		},
		// 实时预览函数
		realTime(data) {
			this.previews = data
		},
		saveMessage() {
			var params = {
				type: 2,
				role_id: this.ruleForm.role_id,
				title: this.ruleForm.title,
				content: this.ruleForm.content,
				class_id: this.$route.query.id,

				file_path: '',
				filesize: 0,
				postfix: '',
				attach_name: ''
			}
			if (this.uploadOrNot) {
				let Size = parseInt(this.uploadInfo.file_size);
				params.file_path = this.ruleForm.file_path
				params.filesize = Size;
				params.postfix = this.uploadInfo.post_fix;
				params.attach_name = this.uploadInfo.file_name
			}
			let success = (data => {
				this.isActive = false
				this.$message.success(data.msg);
				setTimeout(() => {
					this.$router.push('/class/notice/index?id=' + this.$route.query.id);
				}, 1000);

			})

			this.$ajax.post('api/message/message', params, { func: { success: success } })

		},
		submitForm(formName) {

			this.ruleForm.role_id.forEach(item => {
				this.typeNumber += item + ','
			})
			this.$refs[formName].validate((valid) => {
				if (valid) {
					this.isActive = true

					if (this.$refs.uploader.uploader.fileList.length > 0) {
						this.fileUpload();
					} else {
						this.saveMessage();
					}
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		resetForm(formName) {
			this.$router.back(-1)
		},


		//上传成功的事件  
		fileSuccess(rootFile, file, message, chunk) {

			var mess = JSON.parse(message);
			mess = handleResponseData(mess)
			if (parseInt(mess.data.status) === 1) {
				this.uploadOrNot = true
				this.ruleForm.file_path = mess.data.file_path;
				this.uploadInfo.file_name = mess.data.file_name;
				this.uploadInfo.file_path = mess.data.file_path;
				this.uploadInfo.post_fix = mess.data.post_fix;

				this.uploadInfo.file_size = file.size;
				this.saveMessage();
			} else if (mess.status === 'fail') {
				this.$message.error(mess.msg + ' ' + file.name)
				this.$refs.uploader.uploader.cancel()
			}
		},
		fileFail(rootFile, file, message, chunk) {

			var mess = eval('(' + message + ')');
			if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
				let callbcak = (data => {
					this.uploadRetryTimes--;
					this.$refs.uploader.uploader.retry(file);
				})
				this.get_access_token(callbcak);
			} else {
				this.$message.error(mess.msg);
			}
		},
		fileSubmit(files, fileList, event) {
			var arrImg = ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'bmp', 'gif', 'png', 'txt']
			var ext = fileList[0].name.split('.').pop();

			if (!arrImg.includes(ext)) {

				this.$message.warning("只支持doc, xls, xlsx, ppt, pdf, txt, jpg, png, gif格式文件")
				this.$refs.uploader.uploader.cancel();
			} else if (fileList[0].size === 0) {

				this.$refs.uploader.uploader.cancel();
				this.$message.error('上传文件大小不能小于0')
				this.selectFileShowImg = true;
			} else {
				this.selectFileOrNot = true;
				this.selectFileShow = false;
			}

		},
		fileRemoved(file) {
			this.ruleForm.file_path = ''
			this.selectFileOrNot = false;
			this.selectFileShow = true;
		},
		fileUpload() {
			this.$refs.uploader.uploader.resume();
		},
	}
}
</script>
<style scoped lang="css">
.cropper_btn {
	background: #fff;
}
.tailoring {
	height: 500px;
}
.tailoring_cropper {
	height: 100%;
}
.tailoring_cropper>div {
	height: 100%;
}
.vue-cropper {
	position: relative;
	width: 100%;
	height: 500px;
	box-sizing: border-box;
	user-select: none;
	-webkit-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	direction: ltr;
	touch-action: none;
	text-align: left;
	background-image: url("");
}
.cropper-box,
.cropper-box-canvas,
.cropper-drag-box,
.cropper-crop-box,
.cropper-face {
	position: absolute;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	user-select: none;
}
.cropper-box-canvas img {
	position: relative;
	text-align: left;
	user-select: none;
	transform: none;
	max-width: none;
	max-height: none;
}
.cropper-box {
	overflow: hidden;
}
.cropper-move {
	cursor: move;
}
.cropper-crop {
	cursor: crosshair;
}
.cropper-modal {
	background: rgba(0, 0, 0, 0.5);
}
.cropper-crop-box {
	/*border: 2px solid #39f;*/
}
.cropper-view-box {
	display: block;
	overflow: hidden;
	width: 100%;
	height: 100%;
	outline: 1px solid #39f;
	outline-color: rgba(51, 153, 255, 0.75);
	user-select: none;
}
.cropper-view-box img {
	user-select: none;
	text-align: left;
	max-width: none;
	max-height: none;
}
.cropper-face {
	top: 0;
	left: 0;
	background-color: #fff;
	opacity: 0.1;
}
.crop-info {
	position: absolute;
	left: 0px;
	min-width: 65px;
	text-align: center;
	color: white;
	line-height: 20px;
	background-color: rgba(0, 0, 0, 0.8);
	font-size: 12px;
}
.crop-line {
	position: absolute;
	display: block;
	width: 100%;
	height: 100%;
	opacity: 0.1;
}
.line-w {
	top: -3px;
	left: 0;
	height: 5px;
	cursor: n-resize;
}
.line-a {
	top: 0;
	left: -3px;
	width: 5px;
	cursor: w-resize;
}
.line-s {
	bottom: -3px;
	left: 0;
	height: 5px;
	cursor: s-resize;
}
.line-d {
	top: 0;
	right: -3px;
	width: 5px;
	cursor: e-resize;
}
.crop-point {
	position: absolute;
	width: 8px;
	height: 8px;
	opacity: 0.75;
	background-color: #39f;
	border-radius: 100%;
}
.point1 {
	top: -4px;
	left: -4px;
	cursor: nw-resize;
}
.point2 {
	top: -5px;
	left: 50%;
	margin-left: -3px;
	cursor: n-resize;
}
.point3 {
	top: -4px;
	right: -4px;
	cursor: ne-resize;
}
.point4 {
	top: 50%;
	left: -4px;
	margin-top: -3px;
	cursor: w-resize;
}
.point5 {
	top: 50%;
	right: -4px;
	margin-top: -3px;
	cursor: e-resize;
}
.point6 {
	bottom: -5px;
	left: -4px;
	cursor: sw-resize;
}
.point7 {
	bottom: -5px;
	left: 50%;
	margin-left: -3px;
	cursor: s-resize;
}
.point8 {
	bottom: -5px;
	right: -4px;
	cursor: se-resize;
}
</style>